"""
测试Json_Utils功能
"""

import os
import tempfile
from com.tools.Json_Utils import JsonUtils


def test_json_utils():
    """
    测试JSON工具类
    """
    # 创建临时目录用于测试
    with tempfile.TemporaryDirectory() as temp_dir:
        print(f"使用临时目录进行测试: {temp_dir}")
        
        # 测试从字符串加载JSON
        print("\n测试从字符串加载JSON:")
        json_str = '{"name": "张三", "age": 30, "city": "北京", "hobbies": ["游泳", "跑步"]}'
        json_obj = JsonUtils(json_str=json_str)
        print("加载的JSON数据:")
        json_obj.pretty_print()
        
        # 测试获取值
        print("\n测试获取值:")
        name = json_obj.get_value("name")
        print(f"姓名: {name}")
        assert name == "张三"
        
        age = json_obj.get_value("age")
        print(f"年龄: {age}")
        assert age == 30
        
        first_hobby = json_obj.get_value("hobbies.0")
        print(f"第一个爱好: {first_hobby}")
        assert first_hobby == "游泳"
        
        # 测试默认值
        address = json_obj.get_value("address", "未知")
        print(f"地址: {address}")
        assert address == "未知"
        
        # 测试设置值
        print("\n测试设置值:")
        json_obj.set_value("address", "上海市浦东新区")
        json_obj.set_value("job", "软件工程师")
        json_obj.set_value("skills.0", "Python")
        json_obj.set_value("skills.1", "Java")
        
        address = json_obj.get_value("address")
        print(f"更新后的地址: {address}")
        assert address == "上海市浦东新区"
        
        # 测试保存到文件
        print("\n测试保存到文件:")
        json_file = os.path.join(temp_dir, "test.json")
        json_obj.save_to_file(json_file)
        print(f"JSON已保存到: {json_file}")
        
        # 测试从文件加载
        print("\n测试从文件加载:")
        json_obj2 = JsonUtils(json_path=json_file)
        loaded_name = json_obj2.get_value("name")
        print(f"从文件加载的姓名: {loaded_name}")
        assert loaded_name == "张三"
        
        # 测试查找所有键
        print("\n测试查找所有键:")
        test_data = '''
        {
            "users": [
                {"name": "张三", "active": true},
                {"name": "李四", "active": false},
                {"name": "王五", "active": true}
            ],
            "settings": {
                "active": false
            }
        }
        '''
        json_obj3 = JsonUtils(json_str=test_data)
        active_values = json_obj3.find_all_keys("active")
        print(f"所有active值: {active_values}")
        assert len(active_values) == 4
        assert True in active_values
        assert False in active_values
        
        # 测试更新所有键
        print("\n测试更新所有键:")
        updated_count = json_obj3.update_all_keys("active", True)
        print(f"更新了 {updated_count} 个active键")
        assert updated_count == 4
        
        active_values = json_obj3.find_all_keys("active")
        print(f"更新后的active值: {active_values}")
        assert all(v == True for v in active_values)
        
        # 测试更新第N个键
        print("\n测试更新第N个键:")
        json_obj4 = JsonUtils(json_str=test_data)
        success = json_obj4.update_nth_key("active", False, 0)
        print(f"更新第1个active键: {success}")
        assert success == True
        
        success = json_obj4.update_nth_key("active", False, 2)
        print(f"更新第3个active键: {success}")
        assert success == True
        
        # 验证更新结果
        active_values = json_obj4.find_all_keys("active")
        print(f"部分更新后的active值: {active_values}")
        assert active_values[0] == False  # 第1个
        assert active_values[2] == False  # 第3个
        
        # 测试删除键
        print("\n测试删除键:")
        json_obj5 = JsonUtils(json_str=test_data)
        success = json_obj5.delete_key("settings.active")
        print(f"删除settings.active键: {success}")
        assert success == True
        
        settings_active = json_obj5.get_value("settings.active")
        print(f"删除后的settings.active值: {settings_active}")
        assert settings_active is None
        
        # 测试数组操作
        print("\n测试数组操作:")
        json_obj6 = JsonUtils.create_empty_object()
        json_obj6.set_value("items.0", "item1")
        json_obj6.set_value("items.1", "item2")
        
        success = json_obj6.add_to_list("items", "item3")
        print(f"向数组添加元素: {success}")
        assert success == True
        
        items = json_obj6.get_value("items")
        print(f"数组内容: {items}")
        assert len(items) == 3
        assert items[-1] == "item3"
        
        # 测试JSON类型和信息
        print("\n测试JSON类型和信息:")
        json_type = json_obj6.get_json_type()
        print(f"JSON类型: {json_type}")
        assert json_type == "object"
        
        info = json_obj6.get_json_info()
        print(f"JSON信息: {info}")
        assert info['type'] == "object"
        assert info['size'] > 0
        
        # 测试JSON合并
        print("\n测试JSON合并:")
        json1 = JsonUtils(json_str='{"name": "张三", "age": 30}')
        json2 = JsonUtils(json_str='{"city": "北京", "job": "工程师"}')
        
        json1.merge_json(json2)
        print("合并后的JSON:")
        json1.pretty_print()
        
        assert json1.get_value("name") == "张三"
        assert json1.get_value("city") == "北京"
        
        # 测试静态方法
        print("\n测试静态方法:")
        # 验证JSON有效性
        valid = JsonUtils.is_valid_json('{"name": "张三"}')
        print(f"有效JSON: {valid}")
        assert valid == True
        
        invalid = JsonUtils.is_valid_json('{"name": "张三"')
        print(f"无效JSON: {invalid}")
        assert invalid == False
        
        # 创建空对象和数组
        empty_obj = JsonUtils.create_empty_object()
        print("空对象类型:", empty_obj.get_json_type())
        assert empty_obj.get_json_type() == "object"
        
        empty_array = JsonUtils.create_empty_array()
        print("空数组类型:", empty_array.get_json_type())
        assert empty_array.get_json_type() == "array"
        
        # 从字典创建
        data = {"key": "value", "number": 42}
        json_from_dict = JsonUtils.from_dict(data)
        print("从字典创建的JSON:")
        json_from_dict.pretty_print()
        assert json_from_dict.get_value("key") == "value"
        assert json_from_dict.get_value("number") == 42
        
        print("\n所有测试通过!")


if __name__ == "__main__":
    test_json_utils()